package com.zzy.controller;

import com.zzy.dao.UserRepository;
import com.zzy.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private HttpSession session;

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public String userLogin(@Valid User user, BindingResult result, Map<String, Object> map) {
        System.out.println(user);
        if (result.hasFieldErrors()) {
            map.put("error", "字段类型有误.");
            return "login";
        }
        User u = userRepository.findByUserNameAndPassword(user.getUserName(), user.getPassword());
        if (u == null) {
            map.put("error", "用户名或密码输入有误.");
            return "login";
        }
        session.setAttribute("user", u);
        return "main";
    }

    @GetMapping("/reg")
    public String userReg() {
        return "reg";
    }

    @PostMapping("/reg")
    public String userReg(@Valid User user, BindingResult result, Map<String, Object> map) {
        System.out.println(user);
        if (result.hasFieldErrors()) {
            map.put("error", "字段类型有误.");
            return "reg";
        }
        User u = userRepository.findByUserName(user.getUserName());
        if (u != null) {
            map.put("error", "用户名已存在,请使用其他用户名");
            return "reg";
        }
        userRepository.save(user);
        return "login";
    }
}
